package handler

import (
	"awesomeProject/app/model"
	"awesomeProject/app/request"
	"awesomeProject/app/verify"
	"strconv"
	"time"

	//"awesomeProject/app/model"
	//"awesomeProject/app/request"
	"awesomeProject/app/response"
	"awesomeProject/app/service"
	//"awesomeProject/app/verify"
	"github.com/gin-gonic/gin"
	//"strconv"
)

type PurchaseHandler struct{}

var (
	purchaseSrv service.PurchaseSrv
	purchaseTypesSrv service.PurchaseTypesSrv
)

func (r *PurchaseHandler) PurchaseTypesMap(ctx *gin.Context) {
	response.Result(ctx, purchaseTypesSrv.All())
	return
}

func (r *PurchaseHandler) Pagination(ctx *gin.Context) {
	var req request.PurchasePagination
	_ = ctx.Bind(&req)
	// 表单验证
	if err := verify.PurchasePagination(&req); err != nil {
		response.Result(ctx, response.ErrInvalidParam.SetMsg(err.Error()))
		return
	}

	response.Result(ctx, purchaseSrv.Pagination(req))
	return
}

func (r *PurchaseHandler) Create(ctx *gin.Context) {
	var req request.PurchaseCreate
	_ = ctx.Bind(&req)
	// 表单校验
	if err := verify.PurchaseCreate(&req); err != nil {
		response.Result(ctx, response.ErrInvalidParam.SetMsg(err.Error()))
		return
	}
	//fillAble := model.PurchaseFillAble{
	//	Link: req.Link,
	//}
	purchase := model.Purchase {
		ItemID: req.ItemID,
		SkuID: req.SkuID,
		OrderSn: req.OrderSn,
		OrderID: req.OrderID,
		Type: req.Type,
		IsDefault: req.IsDefault,
		Sort: 0,
		CreateAt: time.Now(),
	}
	purchase.Link = req.Link
	// global.LoggerOut(purchase.CreateAt)

	response.Result(ctx, purchaseSrv.Create(purchase))
	return
}

func (r PurchaseHandler) Show(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	err, Purchase := purchaseSrv.FindByID(uint(id))
	if err != nil {
		response.Result(ctx, response.ErrQuery.SetMsg(err.Error()))
	}
	response.Result(ctx, response.OK.WithData(Purchase))
	return
}

func (r *PurchaseHandler) Update(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	var req request.PurchaseUpdate
	_ = ctx.ShouldBindJSON(&req)
	if err := verify.PurchaseUpdate(&req); err != nil {
		response.Result(ctx, response.ErrInvalidParam.SetMsg(err.Error()))
		return
	}
	purchase := model.Purchase {
		ItemID: req.ItemID,
		SkuID: req.SkuID,
		OrderSn: req.OrderSn,
		OrderID: req.OrderID,
		Type: req.Type,
		IsDefault: req.IsDefault,
		Sort: req.Sort,
	}
	purchase.Link = req.Link

	response.Result(ctx, purchaseSrv.Update(uint(id), purchase))
	return
}

func (r *PurchaseHandler) Del(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	response.Result(ctx, purchaseSrv.Del(uint(id)))
	return
}

func (r *PurchaseHandler) ChangeDefault(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	isDefault, _ := strconv.Atoi(ctx.Param("is_default"))
	response.Result(ctx, purchaseSrv.ChangeIsDefault(uint(id),int(isDefault)))
	return
}
